Streamline Your Website with Bootstrap Table Pagination (Source code)

Faraz

By Faraz -

Make your website more user-friendly with Bootstrap Table Pagination. This easy tutorial will teach you how to add pagination to your tables and make browsing a breeze.


how to add pagination to bootstrap tables.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Bootstrap Table Pagination is a valuable tool for any website that contains large amounts of data. This feature allows you to break up large tables into smaller, more manageable pages, making it easier for users to navigate and find the information they need. In this article, we will provide a step-by-step guide on how to implement Bootstrap Table Pagination on your website, and explore the benefits it can bring to your users. By following this guide, you can streamline your website and improve the user experience, making it more efficient and user-friendly. Whether you are a beginner or an experienced web developer, this article will provide all the information you need to get started with Bootstrap Table Pagination.

Pagination is a valuable feature for large tables that contain a lot of data. Here are some of the benefits of using pagination:

  • Improved user experience: Pagination allows users to navigate through large tables with ease, making it more user-friendly and efficient. Users can easily find the information they need without having to scroll through large amounts of data.
  • Increased speed: Large tables can be slow to load, especially on mobile devices or slower internet connections. By breaking up the table into smaller pages, you can reduce the amount of data that needs to be loaded at once, making your website faster and more responsive.
  • Better organization: With pagination, you can organize your data into logical groups, making it easier for users to find the information they need. For example, you could organize a table of products by category or price range, allowing users to easily find the products they are interested in.
  • More efficient use of screen space: Large tables can take up a lot of screen space, especially on smaller devices. By using pagination, you can reduce the amount of space the table takes up, allowing you to include other content on the page.

Overall, pagination is an essential feature for any website that contains large tables of data. By improving the user experience, increasing speed, and providing better organization, pagination can help you create a more efficient and user-friendly website.

Let's start making an amazing Bootstrap table pagination using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Project: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our Bootstrap table.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

The <!DOCTYPE html> declaration is the document type declaration for an HTML document, indicating that the document is an HTML5 document.

The html tag indicates the start of the HTML document, and the lang attribute specifies the language of the document. The head tag contains metadata about the document, including the title, character encoding, and viewport information.

The title tag sets the title of the web page. The meta tag specifies the character encoding and viewport properties of the web page.

The link tag includes external stylesheets that the web page uses. In this case, it includes the Bootstrap CSS file and a custom CSS file named styles.css.

The body tag contains the visible content of the web page.

The container class defines a container for the web page content, and the header_wrap and num_rows classes define a header section for the table with a dropdown menu that allows users to select the number of rows to display.

The tb_search class contains a search input field that allows users to filter the table based on the search query.

The table tag defines the Bootstrap table, with the table-striped class for striped rows and the table-class class for custom styling. The thead tag contains the table headers, and the tbody tag contains the table rows with data.

This is the basic structure of our Bootstrap table pagination using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the table is in place, the next step is to add styling to the table and pagination using custom CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our Bootstrap table pagination.

Here's a breakdown of what each selector and property does:

body: Sets the background color of the entire web page to a light gray color (#eee).

table th, table td: Centers the text within the header cells and data cells of HTML tables.

table tr:nth-child(even): Alternates the background color of every other row in a table to a slightly darker shade of gray (#e4e3e3).

th: Sets the background color of header cells in tables to a dark gray color (#333) and the text color to white (#fff).

.pagination: Removes any margins around pagination links.

.pagination li:hover: Changes the cursor to a pointer when hovering over pagination links.

.header_wrap: Adds padding of 30 pixels on the top and bottom of the header area of the web page.

.num_rows: Sets the width of an element with class "num_rows" to 20% of its container width and floats it to the left side of the container.

.tb_search: Sets the width of an element with class "tb_search" to 20% of its container width and floats it to the right side of the container.

.pagination-container: Sets the width of an element with class "pagination-container" to 70% of its container width and floats it to the left side of the container.

.rows_count: Sets the width of an element with class "rows_count" to 20% of its container width, floats it to the right side of the container, and aligns its text to right.

This will give our Bootstrap table pagination an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body{

  background-color: #eee; 
}

table th , table td{
  text-align: center;
}

table tr:nth-child(even){
  background-color: #e4e3e3
}

th {
background: #333;
color: #fff;
}

.pagination {
margin: 0;
}

.pagination li:hover{
  cursor: pointer;
}

.header_wrap {
padding:30px 0;
}
.num_rows {
width: 20%;
float:left;
}
.tb_search{
width: 20%;
float:right;
}
.pagination-container {
width: 70%;
float:left;
}

.rows_count {
width: 20%;
float:right;
text-align:right;
color: #999;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript for pagination and search.

This code takes an HTML table with a given ID ('#table-id') and adds pagination to it.

The function getPagination() is the main function that adds pagination. It takes the table ID as a parameter and sets up an event listener for changes to the '#maxRows' selector. This selector is used to set the maximum number of rows per page. When the selector is changed, the function calculates the total number of rows in the table, hides rows that exceed the maximum number of rows, and adds pagination links at the bottom of the table. The links allow the user to navigate between pages.

The showig_rows_count() function is used to display the number of rows shown on the current page out of the total number of rows in the table.

The default_index() function adds an ID column to the table, and assigns a unique ID to each row.

The FilterkeyWord_all_table() function is used to search for a keyword in all columns of the table. It hides rows that do not match the keyword and displays those that do.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

getPagination('#table-id');
$('#maxRows').trigger('change');
function getPagination (table){

    $('#maxRows').on('change',function(){
      $('.pagination').html('');						// reset pagination div
      var trnum = 0 ;									// reset tr counter 
      var maxRows = parseInt($(this).val());			// get Max Rows from select option
      
      var totalRows = $(table+' tbody tr').length;		// numbers of rows 
     $(table+' tr:gt(0)').each(function(){			// each TR in  table and not the header
       trnum++;									// Start Counter 
       if (trnum > maxRows ){						// if tr number gt maxRows
         
         $(this).hide();							// fade it out 
       }if (trnum <= maxRows ){$(this).show();}// else fade in Important in case if it ..
     });											//  was fade out to fade it in 
     if (totalRows > maxRows){						// if tr total rows gt max rows option
       var pagenum = Math.ceil(totalRows/maxRows);	// ceil total(rows/maxrows) to get ..  
                             //	numbers of pages 
       for (var i = 1; i <= pagenum ;){			// for each page append pagination li 
       $('.pagination').append('<li data-page="'+i+'">\
                    <span>'+ i++ +'<span class="sr-only">(current)</span></span>\
                  </li>').show();
       }											// end for i 
   
       
    } 												// end if row count > max rows
    $('.pagination li:first-child').addClass('active'); // add active class to the first li 
      
      //SHOWING ROWS NUMBER OUT OF TOTAL DEFAULT
     showig_rows_count(maxRows, 1, totalRows);
      //SHOWING ROWS NUMBER OUT OF TOTAL DEFAULT

      $('.pagination li').on('click',function(e){		// on click each page
      e.preventDefault();
      var pageNum = $(this).attr('data-page');	// get it's number
      var trIndex = 0 ;							// reset tr counter
      $('.pagination li').removeClass('active');	// remove active class from all li 
      $(this).addClass('active');					// add active class to the clicked 
      
      //SHOWING ROWS NUMBER OUT OF TOTAL
     showig_rows_count(maxRows, pageNum, totalRows);
      //SHOWING ROWS NUMBER OUT OF TOTAL
      
       $(table+' tr:gt(0)').each(function(){		// each tr in table not the header
         trIndex++;								// tr index counter 
         // if tr index gt maxRows*pageNum or lt maxRows*pageNum-maxRows fade if out
         if (trIndex > (maxRows*pageNum) || trIndex <= ((maxRows*pageNum)-maxRows)){
           $(this).hide();		
         }else {$(this).show();} 				//else fade in 
       }); 										// end of for each tr in table
        });										// end of on click pagination list
  });
}	

// SI SETTING
$(function(){
// Just to append id number for each row  
default_index();
});

//ROWS SHOWING FUNCTION
function showig_rows_count(maxRows, pageNum, totalRows) {
 //Default rows showing
      var end_index = maxRows*pageNum;
      var start_index = ((maxRows*pageNum)- maxRows) + parseFloat(1);
      var string = 'Showing '+ start_index + ' to ' + end_index +' of ' + totalRows + ' entries';               
      $('.rows_count').html(string);
}

// CREATING INDEX
function default_index() {
$('table tr:eq(0)').prepend('<th> ID </th>')

        var id = 0;

        $('table tr:gt(0)').each(function(){	
          id++
          $(this).prepend('<td>'+id+'</td>');
        });
}

// All Table search script
function FilterkeyWord_all_table() {

// Count td if you want to search on all table instead of specific column

var count = $('.table').children('tbody').children('tr:first-child').children('td').length; 

      // Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("search_input_all");
var input_value =     document.getElementById("search_input_all").value;
      filter = input.value.toLowerCase();
if(input_value !=''){
      table = document.getElementById("table-id");
      tr = table.getElementsByTagName("tr");

      // Loop through all table rows, and hide those who don't match the search query
      for (i = 1; i < tr.length; i++) {
        
        var flag = 0;
         
        for(j = 0; j < count; j++){
          td = tr[i].getElementsByTagName("td")[j];
          if (td) {
           
              var td_text = td.innerHTML;  
              if (td.innerHTML.toLowerCase().indexOf(filter) > -1) {
              //var td_text = td.innerHTML;  
              //td.innerHTML = 'shaban';
                flag = 1;
              } else {
                //DO NOTHING
              }
            }
          }
        if(flag==1){
                   tr[i].style.display = "";
        }else {
           tr[i].style.display = "none";
        }
      }
  }else {
    //RESET TABLE
    $('#maxRows').trigger('change');
  }
}

Final Output:

how to add pagination to bootstrap tables.gif

Conclusion:

In conclusion, Bootstrap Table Pagination is an essential feature for any website that contains large tables of data. By breaking up tables into smaller pages, you can improve the user experience and make browsing more efficient. In this article, we have provided a step-by-step guide on how to implement Bootstrap Table Pagination on your website, including how to add the Bootstrap Pagination plugin to your project and how to customize the appearance of the pagination controls. We have also discussed the benefits of using Bootstrap Table Pagination, including improved user experience, increased efficiency, and a more user-friendly website. We hope that this article has provided you with the information you need to implement Bootstrap Table Pagination on your website and improve the overall user experience for your visitors.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺